use std::{cell::RefCell, rc::Rc};

use deno_core::{op2, v8, OpState};
use QcCore::scene_system::scene::Scene;
use QcUI::component::Canvas;

use crate::utils::GoExt;

pub mod button;
pub mod canvas;
pub mod label;
pub mod panel;
pub mod textbox;
pub mod widget;

#[op2]
pub fn opGetUiNode<'a>(
    state: &mut OpState,
    scope: &mut v8::HandleScope<'a>,
    #[string] name: &str,
) -> v8::Local<'a, v8::Value> {
    let scene = state.borrow_mut::<*mut Scene>();
    let scene = unsafe { &mut **scene };

    if let Some(index) = scene.get_main_canvas() {
        if let Some(canvas) = scene[index].getComponent::<Canvas>() {
            if let Some((index, node)) = canvas.get_ui_node_by_name(name) {
                let type_name = node.get_value().typetag_name();
                let node = v8::Object::new(scope);
                GoExt::set_uuid(scope, node, index);
                GoExt::set_prototype(scope, node, &type_name);
                return node.into();
            }
        }
    }

    v8::undefined(scope).into()
}
